(function(){
    var writeHead = new Vue({
        el:'#write-head',
        data:{
            postData:{
                thumb:'',
                cats:[],
                collections:[]
            },
            cat:'',
            collection:'',
            locked:false,
            showLib:false,
            b2_write_data:{
                "cats":[{"id":4,"name":"category 2"},{"id":1,"name":"Uncategorized"}],
                "cats_default":"1",
                "collection":'',
                "collections":[],
            },
            cats:[{"id":4,"name":"category 2"},{"id":1,"name":"Uncategorized"}],
        },
        mounted(){
            if(this.b2_write_data.cats_default){
                this.postData.cats = [parseInt(this.b2_write_data.cats_default)]
                this.postData.collections = [parseInt(this.b2_write_data.collections_default)]
            }

            const select = document.querySelector('.write-select-box select')

            if(select){
                select.onchange = (even)=>{
                    const id = parseInt(even.target.value)
                    if(this.postData.cats.length > 3 || this.postData.cats.indexOf(id) !== -1 || id == -1) return
                    this.postData.cats.push(id)
                }
            }
        },
        methods:{
            showImgLib(){
                this.showLib = true
                writeEditor.imgTable = 'lib'
                writeEditor.showImageBoxAc('image')
            },
            catPicked(id){
                for (let i = 0; i < this.cats.length; i++) {
                    if(this.cats[i].id == id){
                        return this.cats[i].name
                    }
                }
            },
            removeCat(id){
                if(this.postData.cats.length <= 1) return
                for (let i = 0; i < this.postData.cats.length; i++) {
                    if(this.postData.cats[i] == id){
                        this.postData.cats.splice(i,1);
                    }
                }
            },
        },
        watch:{

        }
    });

    var writeEditor = new Vue({
        el: '#b2-editor-box',
        data:{
            imgTable:'upload',
            videoTable:'upload',
            showImageBox:false,
            showVideoBox:false,
            showPostBox:false,
            showFileBox:false,
            locked:{
                next:false,
                per:false
            },
            paged:1,
            imageList:[],
            imagePages:'',
            videoList:[],
            videoPages:'',
            thumb:'',
            thumbPicked:false,
            _locked:false,
            imagePicked:[],
            roles:{
                hidden:false,
                video:false,
                file:false
            },
            b2_write_data:{
                "custom_code":[
                    {
                        "type":"text"
                    }
                ],
                "cats":[

                ],
                "cats_default":"1",
                "collections":[

                ],
                "collections_default":"0",
                "edit_cats":[

                ],
                "edit_collections":[

                ],
                "edit_roles":[

                ],
                "edit_customs":[

                ],
                "edit_thumb":"",
                "edit_tags":[

                ],
                "edit_excerpt":"",
                "edit_content":"",
                "edit_title":"",
                "post_id":"0",
                "from":{
                    "url":false,
                    "name":false
                },
                "download_edit":""
            }
        },
        mounted(){
            tinymce.init({
                selector: '#mytextarea',
                body_class:'entry-content',
                content_css:b2_global.site_info.site_uri+'/Assets/fontend/style.css',
                icons: 'b2',
                content_style: "body {padding: 10px}",
                body_style: '.entry-content {margin:16px}',
                language:b2_global.language,
                base_url: b2_global.site_info.site_uri+'/Assets/fontend/library/tinymce',
                suffix: '.min',
                statusbar: false,
                link_context_toolbar: true,
                contextmenu: false,
                menubar:false,
                mobile: {
                    toolbar_sticky:true,
                },
                min_height:400,
                toolbar_sticky:true,
                relative_urls: false,
                remove_script_host: false,
                default_link_target: "_blank",
                image_advtab:true,
                plugins: 'code,lists,advlist,autoresize,codesample,link,hr,fullscreen,image,paste,b2preview',
                //alignleft aligncenter alignright alignjustify
                toolbar1:'bold italic forecolor backcolor | heading blockquote codesample numlist bullist | alignment | link b2imagelibrary b2video hr | insertShotCode | removeformat | fullscreen',
                image_caption: true,
                content_style: 'img {max-width: 100%;}',
                oninit : "setPlainText",
                paste_auto_cleanup_on_paste : true,
                paste_remove_styles: true,
                paste_remove_styles_if_webkit: true,
                paste_strip_class_attributes: true,
                setup: (editor)=>{
                    //重写标题按钮
                    editor.ui.registry.addToggleButton('heading', {
                        icon: 'heading',
                        tooltip:'Title',
                        onAction: function (_) {
                            editor.execCommand('mceToggleFormat', false, 'h2');
                        },
                        onSetup: function (api) {
                            editor.formatter.formatChanged('h2', function (state) {
                                api.setActive(state);
                            });
                        }
                    });

                    editor.ui.registry.addGroupToolbarButton('alignment', {
                        icon: 'align-justify',
                        tooltip: 'Alignment',
                        items: 'alignleft aligncenter alignright | alignjustify'
                    });

                    editor.ui.registry.addMenuButton('insertShotCode', {
                        text: 'insert shot code',
                        tooltip:'insert shot code Text',
                        fetch:(callback)=>{
                            var items = [
                                {
                                    type: 'menuitem',
                                    text: 'insert hidden content',
                                    onAction: function () {
                                        editor.insertContent('<p>[content_hide]</p><p>'+b2_global.js_text.global.editor_hidden_content+'</p><p>[/content_hide]</p>');
                                    }
                                },
                                {
                                    type: 'menuitem',
                                    text: 'Insert Post',
                                    onAction: ()=>{
                                        this.showPostBox = true
                                    }
                                },
                                {
                                    type: 'menuitem',
                                    text: 'Insert File',
                                    onAction: ()=>{
                                        this.showFileBox = true
                                    }
                                },
                            ];
                            callback(items);
                        }
                    });

                    //图片按钮
                    editor.ui.registry.addIcon('b2-image-library', '<svg class="Zi Zi--InsertImage" width="24" height="24"><path d="M21 17.4c0 .9-.9 1.6-2 1.6H5c-1.1 0-2-.7-2-1.6V6.6C3 5.7 3.9 5 5 5h14c1.1 0 2 .7 2 1.6v10.8zm-9.4-3.9a.5.5 0 01-.9 0l-1.3-2a.5.5 0 00-.8 0l-2.2 3.8a.5.5 0 00.5.7h10.3a.5.5 0 00.4-.7l-3-5.5a.5.5 0 00-.9 0l-2.1 3.7z" fill-rule="evenodd"/></svg>');
                    editor.ui.registry.addButton('b2imagelibrary', {
                        tooltip: "Insert image",
                        icon: 'b2-image-library',
                        onAction: this.showImageBoxAc
                    });

                    //视频按钮按钮
                    editor.ui.registry.addIcon('b2-video', '<svg class="Zi Zi--InsertVideo" width="24" height="24"><path d="M10.5 15c-.4.3-.8 0-.8-.5v-5c0-.6.4-.8.8-.5l4.3 2.5c.5.3.5.7 0 1L10.5 15zM5 5S3 5 3 7v10s0 2 2 2h14c2 0 2-2 2-2V7c0-2-2-2-2-2H5z" fill-rule="evenodd"/></svg>');
                    editor.ui.registry.addButton('b2video', {
                        tooltip: "Insert video",
                        icon: 'b2-video',
                        onAction: this.showVideoBoxAc
                    });

                },
                init_instance_callback:(editor)=>{
                    if(this.b2_write_data.post_id != 0){
                        this.getCountent(editor)
                    }
                }
            });
        },
        methods:{

            getCountent(editor){
                this.$http.post(b2_rest_url+'getWriteCountent','post_id='+b2_write_data.post_id).then(res=>{
                    editor.setContent(res.data);
                })
            },

            showImageBoxAc(){
                this.showImageBox = true
                this.getAttachments('image')
            },

            showVideoBoxAc(){
                this.showVideoBox = true
                this.getAttachments('video')
            },

            getAttachments(type){
                if(this.locked.next || this.locked.per ) return
                this.locked.next = true
                this.locked.per = true
                this.$http.post(b2_rest_url+'getCurrentUserAttachments','paged='+this.paged+'&type='+type).then(res=>{
                    if(type === 'image'){
                        this.imageList = res.data.data
                        this.imagePages = res.data.pages
                    }else{
                        this.videoList = res.data.data
                        this.videoPages = res.data.pages
                    }
                    this.locked.next = false
                    this.locked.per = false
                })
            },
            close(type){
                if(type == 'image'){
                    this.showImageBox = false
                    writeHead.showLib = false
                }
                if(type === 'video'){
                    this.showVideoBox = false
                }
                if(type === 'post'){
                    this.showPostBox = false
                }
                if(type === 'file'){
                    this.showFileBox = false
                }
                this.paged = 1
            },
            next(type){
                if(type === 'image'){
                    if(this.paged >= this.imagePages){
                        this.locked.next = true
                        return
                    }
                }else{
                    if(this.paged >= this.videoPages){
                        this.locked.next = true
                        return
                    }
                }

                this.paged++
                this.getAttachments(type)
            },
            per(type){
                if(this.paged == 1){
                    this.locked.per = true
                    return
                }
                this.paged--
                this.getAttachments(type)
            },
            picked(type,src){
                if(type == 'image'){

                    if(writeHead.showLib){
                        this.imagePicked = []
                        this.imagePicked[0] = src
                        return
                    }

                    if(this.thumbPicked){
                        this.thumb = src
                    }else{
                        if(this.imagePicked.indexOf(src) !== -1){
                            this.imagePicked.splice(this.imagePicked.findIndex(item => item === src), 1)
                        }else{
                            this.imagePicked.push(src)
                        }
                    }
                }

                if(type == 'video'){
                    if(this.videoPicked.indexOf(src) !== -1){
                        this.videoPicked.splice(this.videoPicked.findIndex(item => item === src), 1)
                    }else{
                        this.videoPicked.push(src)
                    }
                }
            },
            fileUpload(event,filetype){
                if(event.target.files.length <= 0) return
                if(this._locked == true) return
                this._locked = true

                if(filetype === 'image'){
                    for (let i = 0; i < event.target.files.length; i++) {
                        let file = event.target.files[i]
                        let url = URL.createObjectURL(file)
                        this.imageList.splice(i,0,{
                            'id':'',
                            'att_url':'',
                            'thumb':'',
                            'file':file
                        })
                    }
                    this.imgTable = 'lib'
                    for (let i = 0; i < this.imageList.length; i++) {
                        if(this.imageList[i].file){
                            let formData = new FormData()
                            formData.append('file',event.target.files[i],event.target.files[i].name)
                            formData.append("post_id", 1)
                            formData.append("type", 'post')
                            this.$http.post(b2_rest_url+'fileUpload',formData).then(res=>{
                                this.imageList[i].att_url = res.data.url
                                this.imageList[i].id = res.data.id
                                this.imageList[i].progress = 0
                                this.imageList[i].file = ''
                                this.imageList[i].thumb = res.data.url
                                this.picked('image',res.data.url)
                                this._locked = false

                            }).catch(err=>{

                                Qmsg['warning'](err.response.data.message,{html:true});
                                this._locked = false
                            })
                        }
                    }
                }else if(filetype === 'video'){
                    for (let i = 0; i < event.target.files.length; i++) {
                        let file = event.target.files[i]
                        this.videoList.splice(i,0,{
                            'id':'',
                            'att_url':'',
                            'thumb':'',
                            'file':file
                        })
                    }

                    this.videoTable = 'lib'
                    for (let i = 0; i < this.videoList.length; i++) {
                        if(this.videoList[i].file){
                            let formData = new FormData()
                            formData.append('file',event.target.files[i],event.target.files[i].name)
                            formData.append("post_id", 1)
                            formData.append("filetype", 'video')
                            formData.append("type", 'post')
                            this.$http.post(b2_rest_url+'fileUpload',formData).then(res=>{
                                this.videoList[i].att_url = res.data.url
                                this.videoList[i].id = res.data.id
                                this.videoList[i].progress = 0
                                this.videoList[i].file = ''
                                this.videoList[i].thumb = res.data.url
                                this.picked('image',res.data.url)
                                this._locked = false

                            }).catch(err=>{

                                Qmsg['warning'](err.response.data.message,{html:true});
                                this._locked = false
                            })
                        }
                    }
                }
            },
            insert(type){
                let html = '';
                if(type == 'image'){

                    if(writeHead.showLib){
                        writeHead.postData.thumb = this.imagePicked[0]
                        this.imagePicked = []
                        this.showImageBox = false
                        writeHead.showLib = false
                        return
                    }

                    if(writeFooter.showLib){
                        if(this.imgTable == 'link'){
                            writeFooter.download[writeFooter.downloadPicked].thumb = document.querySelector('#imageLink').value
                        }else{
                            writeFooter.download[writeFooter.downloadPicked].thumb = this.imagePicked[0]
                        }
                        this.imagePicked = []
                        this.showImageBox = false
                        writeFooter.showLib = false
                        return
                    }

                    if(this.imgTable == 'link'){
                        let src = document.querySelector('#imageLink').value
                        src = src.split("\n")
                        if(src.length > 0){
                            for (let i = 0; i < src.length; i++) {
                                html += '<p><img src="'+src[i]+'" /></p>';
                            }
                        }
                    }else{
                        for (let i = 0; i < this.imagePicked.length; i++) {
                            html += '<p><img src="'+this.imagePicked[i]+'" /></p>';
                        }
                    }

                    if(html){
                        this.imagePicked = []
                        this.showImageBox = false
                    }
                }

                if(type === 'video'){
                    if(this.videoTable === 'lib'){
                        if(this.videoPicked.length > 0){
                            for (let i = 0; i < this.videoPicked.length; i++) {
                                html += '<p>[b2player src="'+this.videoPicked[i]+'" poster=""]</p>';
                            }
                        }
                    }

                    if(this.videoTable === 'link'){
                        html = '<p>[b2player src="'+document.querySelector('#videoLink').value+'" poster="'+document.querySelector('#videoThumb').value+'"]</p>'
                    }

                    if(this.videoTable === 'html'){
                        html = document.querySelector('#videoHtml').value
                    }

                    if(html){
                        this.videoPicked = []
                        this.showVideoBox = false
                    }
                }

                if(html){
                    console.log(html)
                    tinymce.activeEditor.insertContent(html);
                }
                return
            },
        }
    });

    var writeFooter = new Vue({
         el:'#write-footer',
        data:{
            role:{
                key:'none',
                money:'',
                credit:'',
                roles:[],
            },
            tags:[],
            tag:'',
            lengthw:false,
            tagsCount:4,
            excerpt:'',
            custom:[],
            show:{
                'download':false,
                'from':false,
                'tag':false,
                'role':false,
                'excerpt':false
            },
            customSettings:[],
            locked:false,
            from:{
                url:'',
                name:''
            },
            download:[
                {
                    url:[
                        {
                            name:'',
                            url:'',
                            tq:'',
                            jy:''
                        }
                    ],
                    name:'资源名称',
                    thumb:'',
                    attr:'',
                    view:'',
                    rightsInput:{
                        lv:'all',
                        role:'free',
                        value:''
                    },
                    rights:[]
                }
            ],
            downloadPicked:0,
            showLib:false,
            lvs:'',
            droles:''
        },
        methods:{
            showSetting(key){
                if(this.show[key] === undefined){
                    this.$set(this.show,key,false)
                }
                this.show[key] = !this.show[key]
            },
            tagChange(e){
                if(this.tags.length > this.tagsCount){
                    this.lengthw = true;
                }
                var val = this.tag.replace(/(，|。)+/g, '');
                if (e.keyCode == 13 || e.keyCode == 32 || e.keyCode == 188 || e.keyCode == 190 || this.tag.indexOf("，")!=-1 || this.tag.indexOf("。")!=-1 || e.type == 'blur') {
                    e.preventDefault();
                    var index = this.tags.indexOf(val);
                    if(index == -1 && val.length > 0 && this.tags.length < this.tagsCount ){
                        this.tags.push(val);
                        this.tag = '';
                    }else{
                        this.tag = '';
                        this.lengthw = false;
                    }
                }
            },
            addTag(tag){
                var that = this;
                if(this.tags.length > this.tagsCount) return;
                if(this.tags.indexOf(tag) != -1){
                    this.dubb = tag;
                    setTimeout(function () {
                        that.dubb = '';
                    }, 100);
                    return;
                }else{
                    this.tags.push(tag);
                }
            },
            removeTag(index){
                this.tags.splice(index,1);
            },
            submit(type){
                if(this.locked == true) return
                this.locked = true
                let content = tinymce.activeEditor.getContent();

                if(this.download[0].url[0].name && this.download[0].url[0].url){
                    //检查下载
                    for (let i = 0; i < this.download.length; i++) {
                        // this.download[i].right
                        if(this.download[i].rights.length == 0){
                            Qmsg['warning'](b2_global.js_text.global.download_right_error,{html:true});
                            this.locked = false
                            return
                        }
                    }
                }

                let data = {
                    title:writeHead.$refs.writeTitle.value,
                    cats:writeHead.postData.cats,
                    collections:writeHead.postData.collections,
                    thumb:writeHead.postData.thumb,
                    content:content,
                    custom:this.customSettings,
                    role:this.role,
                    tags:this.tags,
                    excerpt:this.excerpt,
                    type:type,
                    post_id:0,
                    from:this.from,
                    download:this.download
                }

                this.$http.post(b2_rest_url+'insertProduct',Qs.stringify(data)).then(res=>{
                    console.log(res)
                    // if(type === 'draft'){
                    //
                    //     Qmsg['success'](b2_global.js_text.global.save_r_success,{html:true});
                    //     this.locked = false
                    //     location.href = res.data
                    // }else{
                    //     location.href = res.data
                    // }
                    //
                    // this.locked = false
                }).catch(err=>{

                    Qmsg['warning'](err.response.data.message,{html:true});
                    this.locked = false
                })
            }
        }
    });

    window.writeHead = writeHead
    window.writeEditor = writeEditor

}).call(this);